package admin

import (
	"strings"

	"gitee.com/sansaniot/ssiot-core/facade/env"
	"gitee.com/sansaniot/ssiot-core/facade/httpserver"
	"gitee.com/sansaniot/ssiot-core/httpmvc"
	"gitee.com/sansaniot/ssiot-core/logger"
	"github.com/shafreeck/cortana"

	"ssadmin/common/constant"
	"ssadmin/common/middleware"
	"ssadmin/common/middleware/database"
	"ssadmin/common/utils"
	_var "ssadmin/common/vars"
	"ssadmin/internal/admin/router"
	"ssadmin/internal/admin/service"
	"ssadmin/internal/task"
)

func Start() {
	args := struct {
		CfgFile string `cortana:"--config, -c, , config file"`
	}{}

	cortana.Parse(&args)

	if args.CfgFile != "" {
		_var.ConfigFile = args.CfgFile
	}

	// 自动增加requestId
	httpserver.RegisterMiddlewareFunction(middleware.RequestId(httpmvc.TrafficKey))
	// 自定义错误处理
	httpserver.RegisterMiddlewareFunction(middleware.CustomError)
	// NoCache is a middleware function that appends headers
	httpserver.RegisterMiddlewareFunction(middleware.NoCache)
	// 跨域处理
	httpserver.RegisterMiddlewareFunction(middleware.Options)
	// Secure is a middleware function that appends security
	httpserver.RegisterMiddlewareFunction(middleware.Secure)

	// 必须，初始化引擎
	httpserver.InitEngine(_var.ConfigFile)
	env.DefaultConfig.Http.Port = env.ConfigOperator.GetInt64("service.admin.port")

	// 自动检测并创建表
	database.Migrate()

	// 默认参数
	initDefaultParam()

	// 启动定时任务
	initTimedTask()

	// 初始业务
	initSystemBiz()

	// 可选，初始化JWT验证方法组
	jwtMiddleware, _ := middleware.AuthInit()
	// 必须，向内核注册自己的业务模块路由，如不使用中间件，则使用InitRouters方法
	httpserver.InitAuthRouters(router.AuthRouters, jwtMiddleware)

	// 启动HTTP服务器
	_ = httpserver.Run(func() {
		//lastUrl, _ := env.Cache.Get(constant.DataSyncUrl)
		// 取本地内存缓存 服务停止不能保证redis能访问
		if len(constant.DataSyncUrlCache) > 0 {
			// 结束时，自动停止数据分发
			if _, err := service.ReqHttp(constant.DataSyncUrlCache, "close", []string{}); err != nil {
				logger.Error(err)
			}
		}
	})
}

func initDefaultParam() {
	//文件路径
	var fileDir = env.ConfigOperator.GetString("service.admin.filepath")
	if len(fileDir) > 0 {
		constant.FilePath = fileDir
	}
	var dataKeep = env.ConfigOperator.GetInt64("service.admin.datakeep")
	if dataKeep > 0 {
		constant.DefaultDataKeepDays = int(dataKeep)
	}
	var ignoreDir = env.ConfigOperator.GetString("service.admin.cleanignore")
	if len(ignoreDir) > 0 {
		constant.CleanIgnore = strings.Split(strings.ReplaceAll(ignoreDir, " ", ""), ",")
	}
}

func initTimedTask() {
	// 每隔10分钟的第11秒执行
	utils.AddCronTask("11 0/10 * * * ?", func() { task.DevStatTask() }, false)
	// 每隔10分钟的第15秒执行
	utils.AddCronTask("15 0/10 * * * ?", func() { task.UserStatTask() }, false)
	// 每天每6小时整点10分清理数据
	utils.AddCronTask("0 10 0/6 * * ?", func() { task.CleanData() }, false)
	// 每30秒按磁盘阈值清理文件
	utils.AddCronTask("0/30 * * * * ?", func() { task.CleanFile() }, true)
}

func initSystemBiz() {
	lastUrl, _ := env.Cache.Get(constant.DataSyncUrl)
	if len(lastUrl) > 0 {
		constant.DataSyncUrlCache = lastUrl
		// 启动时，自动数据分发
		go func() {
			if _, err := service.ReqHttp(lastUrl, "open", []string{}); err != nil {
				logger.Error(err)
			}
		}()
	}
}
